package va.radiomaria.audio;

import java.io.IOException;
import java.net.MalformedURLException;

import javax.media.ControllerListener;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;

import va.radiomaria.gui.DataModel;
import va.radiomaria.gui.LoggerInstance;

/**
 * Plays audio files on the systems default audio output device.
 */
public class DefaultAudioPlayer implements AudioPlayer {

	private Player player = null;
	private ID3Reader id3Reader = null;

	public DefaultAudioPlayer() {
		Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
		Format input2 = new AudioFormat(AudioFormat.MPEG);
		Format output = new AudioFormat(AudioFormat.LINEAR);
		PlugInManager.addPlugIn("com.sun.media.codec.audio.mp3.JavaDecoder",
				new Format[] { input1, input2 }, new Format[] { output },
				PlugInManager.CODEC);
	}

	public boolean playSong(String url) {
		try {
			if (player != null) {
				player.stop();
				player.close();
			}
			player = Manager.createPlayer(new MediaLocator(url));	
			player.start();
			return true;
		}
		catch (NoPlayerException e) {
			DataModel.getInstance().addConsoleOutput("Song at " + url + " is not reachable", LoggerInstance.AUDIO);
			return false;
		}
		catch (MalformedURLException e) {
			DataModel.getInstance().addConsoleOutput("Song at " + url + " is not reachable", LoggerInstance.AUDIO);
			return false;
		}
		catch (IOException e) {
			DataModel.getInstance().addConsoleOutput("Song at " + url + " is not reachable", LoggerInstance.AUDIO);
			return false;
		}
	}

	public void stop() {
		if (player != null) {
			player.stop();
		}
	}

	public void resume() {
		if (player != null) {
			player.start();
		}
	}

	public String getSongDescription() {
		return "Currently playing " + id3Reader.getSongTitle()
				+ " performed by " + id3Reader.getArtist() + " ("
				+ id3Reader.getGenre() + ")";
	}
	
	public void addControllerListener(ControllerListener controllerListener){
		player.addControllerListener(controllerListener);
	}
}
